﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using yaTDL.Core.MVVM;

namespace yaTDL
{
    /// <summary>
    /// Interaction logic for InputBox.xaml
    /// </summary>
    public partial class InputBox : Window
    {
        public InputBox()
        {
            InitializeComponent();


            this.Top = Application.Current.MainWindow.Top + ((Application.Current.MainWindow.Height - this.Height) / 2);
            this.Left = Application.Current.MainWindow.Left + ((Application.Current.MainWindow.Width - this.Width) / 2);
            this.Owner = App.Current.MainWindow;

            this.KeyDown += new KeyEventHandler(InputBox_KeyDown);
            this.KeyUp += new KeyEventHandler(InputBox_KeyUp);

            this.Loaded += (s, e) =>
            {
                if (!textBox1.IsFocused)
                {
                    textBox1.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(delegate()
                    {
                        textBox1.Focus();
                    }));
                }

                if (!String.IsNullOrEmpty(textBox1.Text))
                {
                    textBox1.SelectAll();
                }                      
            };
        }



        void InputBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                if ((this.DataContext as InputBoxViewModel).CancelCommand.CanExecute(null))
                {
                    (this.DataContext as InputBoxViewModel).CancelCommand.Execute(null);
                }
            }
            else if (e.Key == Key.Enter && enterDown)
            {
                if ((this.DataContext as InputBoxViewModel).OkCommand.CanExecute(null))
                {
                    (this.DataContext as InputBoxViewModel).OkCommand.Execute(null);
                }

                enterDown = false;
            }
        }

        void InputBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                enterDown = true;
            }
        }


        bool enterDown = false;



    }
}
